import {imageUtil} from "./ImageUtil";
import api from './api'
import './ELEMENT'

Vue.prototype.$ImgUtil = imageUtil
Vue.prototype.$api = api
import("./tools")
import("./drawUtils")
import CreateSelectItem from "@/views/handler/createSelectItem.vue";
const initVue = function () {
  new Vue({
    el: '#toolbar',
    components: {
      CreateSelectItem
    },
    data: function () {
      return {
        questions: [],
        freeRect: [],
        change: 1,
        ts: '',
        visible: true,
        scale: 100,
        canvasList: [],
        canvasIndex: 0,
        parseId: null,
        currentSubjective: {
          questionId: null,
          questionIndex: null
        },
        templates: [],
        hiddenAddItem: false,
        setting: {
          f: 0,
          x: 0,
          y: 0,
          sw: 0,
          sh: 0,
          n: 0,
          ai: 0,
          s: 0,
          target: null

        },
        sort: 'xy',
        createSelect: {
          w: 47,
          h: 16.5,
          s: 16,
          n: 10,
          f: 'h',
        },
        config: {},
        eventList: [],
        model: 'default',//point:定位点;
        activeName: 'subjective',
        save: [],
        pages: [
          {
            label: '1',
            value: 0
          }
        ]
      }
    },
    watch: {


      activeName: function (m) {
        this.toDefault()
        this.handleRefresh()
      },
      canvasIndex: function (n) {
        this.canvasList.forEach((item, index) => {
          item.canvas.wrapperEl.style.position = 'absolute'
          if (n !== index) {
            item.canvas.wrapperEl.style.display = 'none'
          } else {
            item.canvas.wrapperEl.style.display = 'block'
          }
        })
      },
      scale: function (n) {
        const canvas = this.canvasList[this.canvasIndex].canvas
        canvas.zoomToPoint(
          {
            x: 0,
            y: 0
          },
          n / 100 // 传入修改后的缩放级别
        )
      },

    },
    computed: {
      questionMap: function () {
        const map = {}
        this.questions.forEach(item => {
          map[item.questionId + item.questionIndex] = item
        })

        return map
      },
      subjectiveQuestions: function () {
        try {
          const map = {}
          this.save.forEach(s => {
            for (let i = 0; i < s.subjective.items.length; i++) {
              let subject = s.subjective.items[i].question;
              let key = subject.questionId + subject.questionIndex
              map[key] = map[key] || []
              map[key].push(subject)
            }

          })
          let ts = this.questions.filter(item => {

            return item.globalType === '主观题'
          });
          let map1 = ts.map((item, index) => {
            let key = item.questionId + item.questionIndex
            let items = map[key] || []
            return {...item, rectNumber: items.length}
          });
          return map1.map((item, index) => {
            if (index + 1 >= map1.length) {
              item.next = null
            } else {
              item.next = map1[index + 1]
            }
            return item;
          })

        } catch (e) {
          console.error(e)
          return []
        }
      },
      objectiveQuestions: function () {
        try {
          return this.questions.filter(item => {
            return item.globalType === '客观题'
          })
        } catch (e) {
          return []
        }
      },
      noFinishObjectiveQuestions: function () {

        try {
          let includeKeys = []
          for (let i = 0; i < this.save.length; i++) {
            let objective1 = this.save[i].objective;
            if (!objective1) {
              continue
            }
            let objective = objective1.items;
            if (objective) {
              objective.questionAreaItems.map(item => {
                let key = item.questionId + item.questionIndex
                includeKeys.push(key)
              })
            }
          }
          return this.objectiveQuestions.filter(item => {
            let key = item.questionId + item.questionIndex
            return !includeKeys.includes(key)
          })
        } catch (e) {
          console.error(e)
          return []
        }
      },
      finishObjectiveQuestions: function () {
        try {
          let includeKeys = []
          for (let i = 0; i < this.save.length; i++) {
            let objective = this.save[i].objective.items;
            if (objective) {
              objective.questionAreaItems.map(item => {
                let key = item.questionId + item.questionIndex
                includeKeys.push(key)
              })
            }
          }
          return this.objectiveQuestions.filter(item => {
            let key = item.questionId + item.questionIndex
            return includeKeys.includes(key)
          })
        } catch (e) {
          return []
        }
      },
      includesCopyToPaperInEventList: function () {
        return this.eventList.filter(item => {
          return item.type === 'copyToPaper'
        }).length > 0
      },
      includesCreateSelectInEventList: function () {
        return this.eventList.filter(item => {
          return item.type === 'createSelect'
        }).length > 0
      },
      templateCache: function () {
        let map = this.templates.map(item => {
          return this.templatesToDetail(item)
        });
        return map || []
      },
      pointers: function () {
        try {
          return this.save[this.canvasIndex].pointer.map(item => {
            let rect = item.getObjects()[0]
            let text = item.getObjects()[1]
            return {
              text: text.text,
              position: [item.left, item.top, rect.width, rect.height],
              target: item
            }
          })
        } catch (e) {
          return []
        }
      }
    },
    methods: {
      handleRefreshCache() {

        if (this.freeRect.length > 0) {

          this.freeRect.forEach(item => {
            this.getCanvas().canvas.add(item)
          })
        }
      },
      freeToSave() {
        if (this.activeName === 'code') {

          let rects = this.freeRect.map(item => {
            return {
              position: this.$draw.getRect(item.consoleRectItems()),
              target: item
            }
          });
          let sortArea = this.$draw.sortArea(rects, rects[0][2] >= rects[0][3] ? 'yx' : 'xy');

          const codeArea = sortArea.map(item => {
            return {
              container: item.sortValue,
              positions: item.target.consoleRectItems().map((item, index) => {
                return {
                  value: index + '', position: item
                }
              })
            }
          })
          this.freeRect = []
          this.save[0].code = this.$draw.draw_rect_student_code(this.getCanvas(0).canvas, codeArea, "", false);
          this.handleRefresh()
        } else if (this.activeName === 'objective') {
          let objective = this.save[this.canvasIndex].objective;

          let items = {
            templateIndex: this.canvasIndex,
            questionAreaItems: [],
          }
          if (objective) {
            items = objective.items;

          }
          let positions = this.freeRect.map((item, nextQuestionIndex) => {
            return {
              position: this.$draw.getRect(item.consoleRectItems()),
              target: {
                positions: item.consoleRectItems().map((position, index) => {
                  return {
                    position: position,
                    value: String.fromCharCode(65 + index)
                  }
                }),
                questionId: this.noFinishObjectiveQuestions[nextQuestionIndex].questionId,
                questionIndex: this.noFinishObjectiveQuestions[nextQuestionIndex].questionIndex,
                paperIndex: this.noFinishObjectiveQuestions[nextQuestionIndex].customQuestionIndex,
                score: this.noFinishObjectiveQuestions[nextQuestionIndex].score,
              }
            }
          });
          let sortArea1 = this.$draw.sortArea(positions, 'xy');
          const length = sortArea1.length
          for (let i = 0; i < length; i++) {
            items.questionAreaItems.push(sortArea1[i].target)
          }
          let drawObjective = this.$draw.draw_objective(this.getCanvas().canvas, items, false);
          this.save[this.canvasIndex].objective = drawObjective
          this.freeRect = []
          this.handleRefresh()

        }
      },
      clearEvent() {
        // this.freeRect = []
        this.eventList.forEach(item => {
          item.off()
        })
        this.eventList = []
      },
      pushFreeRectByItems(canvas, items1) {
        let drawSelectSingleItemByItems = this.$draw.draw_select_single_item_by_items(canvas, items1
          , false, false);
        drawSelectSingleItemByItems.lockScalingX = true
        drawSelectSingleItemByItems.lockScalingY = true
        drawSelectSingleItemByItems.hasControls = false
        drawSelectSingleItemByItems.toColor('rgba(255,0,0,0.5)')
        this.$draw.onDeleteButton(drawSelectSingleItemByItems, canvas)

        canvas.add(drawSelectSingleItemByItems)
        //判断是否和别的元素重合
        canvas.forEachObject(function (obj) {
          if (obj === drawSelectSingleItemByItems) return;
          if (drawSelectSingleItemByItems.intersectsWithObject(obj)) {
            canvas.remove(drawSelectSingleItemByItems)
          }
        });
        //如果成功添加再存
        if (canvas.getObjects().includes(drawSelectSingleItemByItems)) {

          this.freeRect.push(drawSelectSingleItemByItems)
        }
      },
      copyToPaper(target) {
        if (this.includesCopyToPaperInEventList) {
          this.clearEvent()
          return
        }
        let canvas = this.getCanvas().canvas;
        let downCallback = (e) => {
          let message = e.absolutePointer;
          // console.log(message)

          let items = target.consoleRectItems();
          const offsetX = message.x - items[0][0]
          const offsetY = message.y - items[0][1]
          let items1 = items
            .map(item => {
              return [item[0] + offsetX, item[1] + offsetY, item[2], item[3]]
            });

          this.pushFreeRectByItems(canvas, items1)
        };
        canvas.on("mouse:down", downCallback)
        this.eventList.push(
          {
            on: downCallback,
            off: () => {
              canvas.off("mouse:down", downCallback)
            },
            type: 'copyToPaper'
          }
        )
      },
      overLookTemplate(item) {
        this.handleRefreshCache()

        this.setting = {}
        this.getCanvas().canvas.remove(item.target)
        this.hiddenAddItem = true
        this.clearEvent()
        this.handleRefresh(false)

      },
      settingChange(name, value) {
        this.setting[name] = value
        const data = {
          w: this.setting.sw,
          h: this.setting.sh,
          n: this.setting.n,
          s: this.setting.s,
          f: this.setting.f,
          x: this.setting.target.left,
          y: this.setting.target.top
        }
        let template = this.$draw.draw_select_single_item_by_config(this.getCanvas().canvas, data, true);
        this.templates = this.templates.map(item => {
          if (this.setting.target === item) {
            this.getCanvas().canvas.remove(item)
            return template
          }
          return item
        })
        this.lookTemplate(template)
      },
      callbackChangeObject(options, canvas) {
        let action = ""
        if (options.transform) {
          action = options.transform.action;
        }
        if (options.target && options.target.removeBody) {
          options.target.removeBody();
        }
        if (options.target && options.target.moveCallback) {
          options.target.moveCallback();
        }
        if (action === "drag") {

        } else if (action === "scale" || action === 'scaleX' || action === 'scaleY') {
          if (this.setting && this.setting.target && this.setting.target === options.target) {
            this.lookTemplate(this.setting.target);
          }
        }
      },
      deleteTemplate(target) {
        this.getCanvas().canvas.remove(target)

        this.templates = this.templates.filter(item => {
          return item !== target
        })
      },
      lookTemplate(target, draw = false) {
        this.setting = this.templatesToDetail(target)
        if (draw) {
          let canvas = this.getCanvas().canvas;
          canvas.getObjects().forEach(item => {
            canvas.remove(item)
          })
          canvas.add(target)
        }
      },
      handCreateSelect() {
        if (this.includesCreateSelectInEventList) {
          this.clearEvent()
          return
        }
        let canvas = this.getCanvas().canvas;
        let on = (e) => {
          const data = {
            ...this.createSelect,
            x: e.absolutePointer.x,
            y: e.absolutePointer.y
          }
          let template = this.$draw.draw_select_single_item_by_config(canvas, data);
          this.templates.push(template)
          this.lookTemplate(template, true)
          this.clearEvent()
        };
        canvas.on("mouse:down", on)
        this.eventList.push({
          on: on,
          off: () => {
            canvas.off("mouse:down", on)
          },
          type: 'createSelect'
        })

      },
      clearSelectItems() {
        if (this.activeName === 'code') {
          this.save.forEach((item, index) => {
            if (item.code) {
              this.canvasList[index].canvas.remove(item.code)
            }
            item.code = null
          });
        }
        if (this.activeName === 'objective') {
          this.save.forEach((item, index) => {
            if (item.objective) {
              item.objective.clear()
            }
            item.objective = null
          });
          let save = this.save.map(item => item);
          this.save = save

        }
      },
      templatesToDetail(item) {
        const rects = item.consoleRectItems();
        let rect = this.$draw.getRect(rects);
        return {
          f: item.fangxiang,
          x: item.left,
          y: item.top,
          sw: rects[0][2],
          sh: rects[0][3],
          n: rects.length,
          ai: item.ai,
          width: rect[2],
          height: rect[3],
          s: item.fangxiang === 'h' ? rects[1][0] - rects[0][0] - rects[0][2] : rects[1][1] - rects[0][1] - rects[0][3],
          target: item
        }
      },
      handleRefresh(remove) {
        let loading = this.$loading();
        try {
          this._handleRefresh(remove)
        } finally {
          loading.close()
        }
      },
      _handleRefresh(remove = true) {
        this.clearEvent()
        if (remove) {
          this.freeRect = []
        }
        if (remove) {
          this.canvasList.forEach(item => {
            item.canvas.getObjects().forEach(o => {
              item.canvas.remove(o)
            })
          });
        }


        if (this.activeName === 'point') {
          const sl = this.save.length
          let b = null
          for (let i = 0; i < sl; i++) {
            let canvas = this.canvasList[i].canvas;
            const item = this.save[i]
            for (let j = 0; j < item.pointer.length; j++) {
              let o = item.pointer[j]
              canvas.add(o)
            }
          }
          this.save.forEach((item, index) => {

          })
        } else if (this.activeName === 'code') {
          if (this.save) {
            let length = this.save.length;
            for (let i = 0; i < length; i++) {
              let item = this.save[i]
              if (item.code) {
                this.canvasList[i].canvas.add(item.code)
              }
            }
          }
        } else if (this.activeName === 'objective') {
          if (this.save) {
            let length = this.save.length;
            for (let i = 0; i < length; i++) {
              let objective = this.save[i].objective;
              if (objective) {
                objective.add()
              }
            }
          }
        } else if (this.activeName === 'subjective') {
          if (this.save) {
            let length = this.save.length;
            for (let i = 0; i < length; i++) {
              let objective = this.save[i].subjective;
              if (objective) {
                objective.add()
              }
            }
          }
        }
      },
      async handleSave() {
        const toPointers = (index) => {

          return this.save.map(page => {
            return {
              pointers: page.pointer.map(item => {
                let rect = item.getObjects()[0]
                return {
                  position: [item.left, item.top, rect.width, rect.height],
                }
              })
            }
          })

        }
        const toStudentIdArea = () => {
          return this.save[0].code.items
        }

        const toObjectiveArea = () => {
          return this.save.map(item => {
            if (item.objective == null) {
              return null
            }
            return item.objective.items
          }).filter(item => item != null)
        }
        const toSubjectiveArea = () => {
          const subjectives = []
          this.save.forEach((item, oi) => {
            if (item.subjective == null) {
              return null
            }
            item.subjective.consolePositions(oi).forEach(position => {
              subjectives.push(position)
            })
          })
            // return item.subjective.consolePositions(oi)
          // }).filter(item => item != null);
          return subjectives
        }
        const loading = this.$loading()
        try {
          let res = await this.$api.saveParseConfig({
            id: this.parseId,
            pointerArea: toPointers(),
            studentIdArea: toStudentIdArea(),
            objectiveArea: toObjectiveArea(),
            subjectiveArea: toSubjectiveArea(),
            finish: 'ok',
            studentIdType: 'pan',

          })
          if (res.code !== 200) {
            alert("保存失败")
            return
          }
          this.$notify({
            title: '保存成功',
            dangerouslyUseHTMLString: false,
            message: `请回到答题卡列表页面`
          });
        } finally {
          loading.close()
        }
      },
      async queryConfig() {

        const url = new URL(window.location.href);
        const params = new URLSearchParams(url.search);
        const parseId = params.get('parseId'); // 返回 'value1'
        this.parseId = parseId
        let res = await this.$api.parseConfigAndQuestions({
          id: parseId
        })
        if (res.code === 200) {
          this.config = res.data.bsPaperParseTemplate
          this.questions = res.data.questions
        } else {
          alert("请求模板失败")
        }
      },
      canvasIndexChange(e) {
        if (this.model === 'point') {
          this.toDefault()
        }
        this.canvasIndex = e;
      },
      deletePointers(target) {
        const remove = this.save[this.canvasIndex].pointer.filter(item => {
          return item === target.target
        })[0]
        this.save[this.canvasIndex].pointer = this.save[this.canvasIndex].pointer.filter(item => {
          return item !== remove
        }).map((item, index) => {
          item.getObjects()[1].text = ((index + 1) + "")
          return item
        })
        let canvas = this.getCanvas().canvas;
        canvas.remove(remove)
        canvas.renderAll()
        this.save = this.save.map(item => {
          return item
        })
      },
      initSave() {
        const length = this.config.imgs.length

        let t = []
        for (let i = 0; i < length; i++) {

          //定位
          let pointer = []
          try {
            pointer = this.config.pointerArea[i].pointers.map((item, index) => {
              return this.$draw.draw_rect_point(this.getCanvas(i).canvas, [item.position[0], item.position[1], item.position[2], item.position[3]], (index + 1) + '', false);
            });
          } catch (e) {

          }
          //考号
          let codeArea = null;
          if (i === 0) {
            codeArea = this.$draw.draw_rect_student_code(this.getCanvas(i).canvas, this.config.studentIdArea, "学号区域", false)
          }

          //客观题
          let objective = null
          let objectiveArea = this.config.objectiveArea;
          if (objectiveArea && objectiveArea.length > i) {
            let pageArea = objectiveArea[i];
            objective = this.$draw.draw_objective(this.getCanvas(i).canvas, pageArea, false);
          }

          //主观题
          let subjectiveArea = this.config.subjectiveArea || [];

          const questions = subjectiveArea.filter(item => {

            return item.templateIndex === i
          }).map(item => {
            const key = item.questionId + item.questionIndex
            let q = this.questionMap[key];
            return {...item, paperIndex: q.paperIndex, score: q.score}
          })
          let drawSubjective = this.$draw.draw_subjective(this.getCanvas(i).canvas, questions, false);

          t.push({
            pointer: pointer,
            code: codeArea,
            objective: objective,
            subjective: drawSubjective,
          })
        }
        this.save = t
        this.handleRefresh()
      },
      async findItemsInImgByConfig(file, config) {

        const res = await this.$api.matchTemplate(file, config)
        if (res.code !== 200) {
          return null;
        }
        return res.data.list || []
      },
      async findItemInImgs(file) {
        let formData = new FormData();
        formData.append("config", JSON.stringify({
          times: 1,
          skill: true
        }))
        formData.append("file", file)
        const res = await this.$api.findItemInImgs(formData)
        if (res.code !== 200) {
          return null;
        }
        return res.data.items
      },
      async pointCallback() {
        let target = this.getCanvas();
        let data1 = target.canvas.TempDiv;
        const x = data1.left
        const y = data1.top
        const w = data1.width
        const h = data1.height
        let base64 = await this.$ImgUtil.croppedToBase64({
          x: x,
          y: y,
          width: w,
          height: h,
          src: target.src
        })
        let blob = this.$ImgUtil.dataURLtoBlob(base64);
        let file = this.$ImgUtil.blobToFile(blob);
        const items = await this.findItemInImgs(file);
        if (items != null && items.length >= 1) {
          const [x_, y_, w_, h_] = items[0]
          let pointer = this.save[this.canvasIndex].pointer;
          let pointGroup = this.$draw.draw_rect_point(this.getCanvas().canvas, [x_ + x, y_ + y, w_, h_], (pointer.length + 1) + '', true);
          pointer.push(pointGroup)
          this.changeModel('point')
        } else {

        }
      },
      async autoRectByTemplateCallback(data) {
        const config = {
          "splitValue": data.s,
          "width": data.width,
          "height": data.height,
          "itemWidth": data.sw,
          "itemHeight": data.sh,
          "itemsSize": data.n,
          "times": 1
        }
        let target = this.getCanvas();
        let data1 = target.canvas.TempDiv;
        const x = data1.left
        const y = data1.top
        const w = data1.width
        const h = data1.height
        let base64 = await this.$ImgUtil.croppedToBase64({
          x: x,
          y: y,
          width: w,
          height: h,
          src: target.src
        })
        let blob = this.$ImgUtil.dataURLtoBlob(base64);
        let file = this.$ImgUtil.blobToFile(blob);
        const itemsList = await this.findItemsInImgByConfig(file, config);
        let items = data.target.consoleRectItems();
        for (let i = 0; i < itemsList.length; i++) {
          let [x_, y_, _1, _2] = itemsList[i][0];
          x_ = x_ + x
          y_ = y_ + y
          // console.log(message)
          const offsetX = x_ - items[0][0]
          const offsetY = y_ - items[0][1]
          let items1 = items
            .map(item => {
              return [item[0] + offsetX, item[1] + offsetY, item[2], item[3]]
            });
          this.pushFreeRectByItems(this.getCanvas().canvas, items1)
        }

      },
      async templateCallback() {
        let target = this.getCanvas();
        let data1 = target.canvas.TempDiv;
        const x = data1.left
        const y = data1.top
        const w = data1.width
        const h = data1.height
        let base64 = await this.$ImgUtil.croppedToBase64({
          x: x,
          y: y,
          width: w,
          height: h,
          src: target.src
        })
        let blob = this.$ImgUtil.dataURLtoBlob(base64);
        let file = this.$ImgUtil.blobToFile(blob);
        const items = await this.findItemInImgs(file);
        if (items == null) {
          this.$message.error("获取失败")
          return
        }
        let drawSelectSingleItemByItems = this.$draw.draw_select_single_item_by_items(target.canvas, items.map(item => {
          item[0] = item[0] + x
          item[1] = item[1] + y
          return item
        }), true, true);
        this.templates.push(drawSelectSingleItemByItems)
        this.lookTemplate(drawSelectSingleItemByItems, true)


      },
      async subjectiveCallback(question) {
        let target = this.getCanvas();
        let data1 = target.canvas.TempDiv;
        let number = data1.width
        console.log(number)
        if (number < 100) {
          alert('框选区域太小停止框选')
          return
        }
        let subjective = this.save[this.canvasIndex].subjective;
        // target.canvas.remove(data1)
        subjective.pushPosition([data1.left, data1.top, data1.width, data1.height], question, true)
        if (question.next) {
          setTimeout(() => {
            this.changeModel('subjective', question.next)
          }, 0)

        }

      },
      async toBase64(src) {
        let res = await this.$api.getBase64FromUrl({src: src});
        if (res.code !== 200) {
          return
        }
        return "data:image/png;base64," + res.data
      },
      getCanvas(index = null) {
        if (index) {
          return this.canvasList[index]
        }
        return this.canvasList[this.canvasIndex];
      },
      toDefault() {
        let canvas = this.getCanvas().canvas;
        if (canvas.toDefault) {
          canvas.toDefault()
          delete canvas.toDefault
        }
      },
      changeModel(model, data) {
        let target = this.getCanvas();
        const canvas = target.canvas
        if (this.model !== 'default') {
          if (canvas.toDefault) {
            canvas.toDefault()
            delete canvas.toDefault
          }
          return
        }
        if (model === 'subjective') {
          this.currentSubjective = data
        }

        let downPoint = null;
        let upPoint = null
        this.model = model
        const canvasMouseDown = (e) => {
          // 鼠标左键按下时，将当前坐标 赋值给 downPoint。{x: xxx, y: xxx} 的格式
          downPoint = e.absolutePointer
          canvas.selection = false // 允许框选
          canvas.TempDiv = new fabric.Rect({
            lockMovementX: true,
            lockMovementY: true,
            selectable: false,
            hasControls: false,
            top: downPoint.y,
            left: downPoint.x,
            width: 1,
            height: 1,
            fill: 'transparent', // 填充色：透明
            stroke: '#000' // 边框颜色：黑色
          })

          canvas.add(canvas.TempDiv)
          // canvas.renderAll()
        }
        // 鼠标在画布上松开
        const canvasMouseUp = (e) => {


          if (this.model === 'point') {
            this.pointCallback()

          } else if (this.model === 'subjective') {
            this.subjectiveCallback(data)
          } else if (this.model === 'template') {
            this.templateCallback()
          } else if (this.model === 'autoRectByTemplate') {
            this.autoRectByTemplateCallback(data)
          } else {
            this.clearEvent();
          }
          clear();
          // 绘制矩形的模式下，才执行下面的代码
          if (this.model !== 'default') {
            this.model = 'default'
          }

        }
        const canvasMouseMove = (e) => {

          if (canvas.TempDiv) {

            let y = Math.max(0, e.absolutePointer.y);

            let x = Math.max(0, e.absolutePointer.x);
            let top = Math.min(downPoint.y, y)
            let left = Math.min(downPoint.x, x)
            let width = Math.abs(downPoint.x - x)
            let height = Math.abs(downPoint.y - y)


            if (canvas.TempDiv) {
              canvas.remove(canvas.TempDiv)
              canvas.TempDiv = new fabric.Rect({
                lockMovementX: true,
                lockMovementY: true,
                selectable: false,
                hasControls: false,
                top: top,
                left: left,
                width: Math.min(Math.abs(target.width - left), width),
                height: Math.min(Math.abs(target.height - top), height),
                fill: 'transparent', // 填充色：透明
                stroke: '#F00' // 边框颜色：黑色
              })
            }
            canvas.add(canvas.TempDiv)
            canvas.renderAll()
          }

        }
        const clearEvent = () => {
          canvas.off('mouse:down', canvasMouseDown)   // 鼠标在画布上按下
          canvas.off('mouse:up', canvasMouseUp)   // 鼠标在画布上按下
          canvas.off('mouse:move', canvasMouseMove)   // 鼠标在画布上按下

        }
        const clear = () => {
          clearEvent()
          canvas.selection = true
          if (canvas.TempDiv) {
            canvas.remove(canvas.TempDiv)
            canvas.TempDiv = null
            canvas.renderAll()

          }
        }
        canvas.toDefault = () => {
          this.model = 'default'
          clear()
        }
        canvas.on('mouse:down', canvasMouseDown)   // 鼠标在画布上按下
        canvas.on('mouse:up', canvasMouseUp)   // 鼠标在画布上按下
        canvas.on('mouse:move', canvasMouseMove)   // 鼠标在画布上按下
      },
      async loadImg(src, name) {
        return new Promise((resolve) => {
          const _this = this
          const image = new Image()
          image.src = src
          image.onload = (source) => {
            const app = document.getElementById("app")
            let node = document.createElement("canvas");
            node.id = name
            node.width = image.width
            node.height = image.height
            app.appendChild(node)
            init(image.src, image.width, image.height)
            resolve()
          }

          function init(src, w, h) {
            const canvas = new fabric.Canvas(name);
            // canvas.on('mouse:move', (e) => {
            //
            //
            canvas.on({
              "object:added": (options) => {
                // alert(1)
                // _this.callbackChangeObject(options, canvas)
                if (options.target.addOther) {
                  options.target.addOther(canvas)
                }
              },
              "object:removed": (options) => {
                // alert(1)
                // _this.callbackChangeObject(options, canvas)
                if (options.target.isDelete && options.target.custom_type === 'subjective') {
                  _this.save[_this.canvasIndex].subjective.removeObject(options.target)
                  return
                }
                if (options.target.isDelete) {
                  _this.freeRect = _this.freeRect.filter(item => {
                    return item !== options.target
                  });
                }
              },
              "object:selected": (options) => {
                _this.callbackChangeObject(options, canvas)
              },
              'object:moving': (options) => {
                options.target.setCoords();
                _this.callbackChangeObject(options, canvas)
              },
              'object:scaling': (options) => {
                _this.callbackChangeObject(options, canvas)
              },
              'object:rotating': (options) => {
                _this.callbackChangeObject(options, canvas)
              },
            });
            _this.canvasList.push({
              src: src,
              canvas: canvas,
              width: w,
              height: h
            })

            fabric.Image.fromURL(src, img => {
              img.set({
                selectable: true,
                move: false,
                left: 0,
                top: 0,
                scaleX: 1,
                scaleY: 1,

              });
              canvas.setBackgroundImage(img)
              canvas.renderAll()
            }, {crossOrigin: 'anonymous'});
          }
        })

      },
      initPageFromSave() {

        let objects = this.getCanvas().canvas.getObjects();
        objects.length
        for (let i = 0; i < length; i++) {
          this.getCanvas().canvas.remove(objects[i])
        }
        if (this.activeName === 'point') {
          this.save[this.canvasIndex].pointer.forEach(item => {
            this.getCanvas().add(item.target)
          })
        }
      },
    },
    async mounted() {
      await this.queryConfig()
      this.pages = this.config.imgs.map((item, index) => {
        return {
          label: (index + 1) + "",
          value: index
        }
      })
      for (let i = 0; i < this.config.imgs.length; i++) {
        const img = this.config.imgs[i]
        let url = await this.toBase64(img.url)
        await this.loadImg(url, "canvas" + i)
      }
      this.initSave()

      // console.log(this.canvasList[0])
      this.canvasList.forEach((item, index) => {
        item.canvas.wrapperEl.style.position = 'absolute'
        if (this.canvasIndex !== index) {
          item.canvas.wrapperEl.style.display = 'none'
        } else {
          item.canvas.wrapperEl.style.display = 'block'
        }
      })
    },
  })
};
initVue()


